package com.gan.simple_init.model.user.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gbw
 * @date 2023/8/9
 */

@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@JsonIgnoreProperties({"enabled","accountNonLocked","accountNonExpired","credentialsNonExpired","authorities"})
public class LoginUser extends SysUser implements UserDetails, Serializable {

    /**
     * 是否管理员 0 不是管理员 1 是管理员
     */
    private Integer isAdmin = 0;

    /**
     * 权限集合
     */
    List<String> roles;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities = new ArrayList<>();

    public LoginUser(Integer isAdmin, List<String> roles) {
        this.isAdmin = isAdmin;
        this.roles = roles;
    }

    public LoginUser() {
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
        if (authorities.isEmpty()){
            authorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return super.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
